# -*- coding: utf-8 -*-
# !/usr/bin/env python
import yaml
from rest_framework.views import APIView
from components.kubernetes.api_config_file_text import api_config_file_text
from utils.K8S import K8sApi
from utils.views import Result, ReturnClass


class DeploymentsConfYaml(APIView):
    """
    获取Deployments yaml配置内容
    """
    def get(self, request):
        data = request.query_params
        deployment_name = data['deployment_name']
        namespace = data['namespace']
        kubernetes_cluster_id = data['kubernetes_cluster_id']

        # 获取 配置的文件，连接api服务器
        kubernetes_cluster_sign_kubeconfig = api_config_file_text(kubernetes_cluster_id)
        if not ReturnClass.if_ok(kubernetes_cluster_sign_kubeconfig):
            return Result.fail_response(msg=ReturnClass.get_value(kubernetes_cluster_sign_kubeconfig))
        k8s_api = K8sApi(ReturnClass.get_value(kubernetes_cluster_sign_kubeconfig))

        try:
            return_data_dict = k8s_api.get_deployment_yaml(deployment_name, namespace)
            #格式化dict为str yaml
            return_data = yaml.dump(return_data_dict, )
        except Exception as e:
            return Result.fail_response(msg=str(e))
        return Result.success_response(data=return_data, msg='查询成功')

    def put(self, request):
        data = request.data
        configuration_yaml_text = data['configuration_yaml_text']
        namespace = data['namespace']
        deployment_name = data['deployment_name']
        kubernetes_cluster_id = data['kubernetes_cluster_id']

        # 获取 配置的文件，连接api服务器
        kubernetes_cluster_sign_kubeconfig = api_config_file_text(kubernetes_cluster_id)
        if not ReturnClass.if_ok(kubernetes_cluster_sign_kubeconfig):
            return Result.fail_response(msg=ReturnClass.get_value(kubernetes_cluster_sign_kubeconfig))
        k8s_api = K8sApi(ReturnClass.get_value(kubernetes_cluster_sign_kubeconfig))

        try:
            configuration_yaml_dict = yaml.load(configuration_yaml_text, Loader=yaml.FullLoader)
            return_data_dict = k8s_api.update_deployment_yaml(deployment_name, namespace, configuration_yaml_dict)
        except Exception as e:
            return Result.fail_response(msg=str(e))
        return Result.success_response(msg='提交成功')